<?php
/*
Plugin Name: LiveChat
Plugin URI: http://www.atop-online.com
Description: Live Chat
Version: 0.0.1
Author: Selver.D && Evan.chen
Author URI: http://www.selverd.com
*/
	add_action('activate_wp-livechat/admin.php', 'livechat_install');
/* menu (DMSGuestbook, Manage) */
	add_action('admin_menu', 'add_live_chat');
	function add_live_chat() {
		add_menu_page(__('Options', 'LiveChat'), __('Chat Room', 'LiveChat'),
		'edit_others_posts', 'wp-livechat', 'chat_room_init', '');
			//add_submenu_page( 'wp-livechat' , __('Options', 'LiveChat'), __('Chat Record', 'LiveChat'), 'edit_others_posts','Manage', 'chat_record_init');
			add_submenu_page( 'wp-livechat' , __('Options', 'LiveChat'), __('Custom Profiler', 'LiveChat'), 'edit_others_posts',
		'Profiler', 'set_profiler_page');
			add_submenu_page( 'wp-livechat' , __('Options', 'LiveChat'), __('Generate File', 'LiveChat'), 'edit_others_posts',
		'Generate', 'gg_options_page_chat');
	}
/*live chat main function */
	function chat_record_init()
	{
		/*get admin option */
		$admin_option = get_livechat_adminoption();

		global $wpdb;
		$table_name = $wpdb->prefix . "chat";
		$sql = "SELECT * FROM $table_name ORDER BY timestamp DESC";
		$chat_rec_array = $wpdb->get_results($sql);
		$chat_rec_num = $wpdb->num_rows;
?>
	<!-- header -->
	<div class="wrap">
    <h2>Live Chat Record</h2>
	<script type="text/javascript">
		function del_rec(){
			if(confirm("are you sure to delete this?"))
			{
				var id = arguments[0]? arguments[0] : '';
				url = document.URL;
				jQuery.post(url,{action:'del',id:id},
							function (){
								window.location.reload();
							}
				);
			}
		}
		function save_option(){
			var page_id = document.getElementById('page_id').value;
			url = document.URL;
			jQuery.post(url,{action:'save_option',page_id:page_id},
						function (){
							window.location.reload();
						}
			);
		}
	</script>
	<!--Page ID:<input type="text" value="<?php echo $admin_option['page_id']?>" id="page_id" style="width: 150px;" /><input type='button' value='Save' onclick='save_option();' />
<br/>-->
    <table width="800" border="1" cellspacing="5" cellpadding="0">
	  <tr>
		<th width="100">Sender</th>
		<th width="300">Text</th>
		<th width="100">Receiver</th>
		<th width="50">Rating</th>
		<th width="150">Date</th>
		<th width="100">Del</th>
	  </tr>
	  <?php
	  foreach($chat_rec_array as $chat_rec)
	  		{
				$user_name = get_user($chat_rec->sender_id)->user_nicename ? get_user($chat_rec->sender_id)->user_nicename : 'Guest' ;
	  	 		$output .= "<tr>";
				$output .= "<td align='center'>".$user_name."</td>";
				$output .= "<td align='center'>".$chat_rec->text."</td>";
				$output .= "<td align='center'>".$chat_rec->receiver_id."</td>";
				$output .= "<td align='center'>".$chat_rec->rating."</td>";
				$output .= "<td align='center'>".$chat_rec->timestamp."</td>";
				$output .= "<td align='center'><input type='button' value='Del' name='$chat_rec->id' onclick='del_rec(this.name);' /></td>";
				$output .= "</tr>";
			}
			echo $output;
	  ?>
	</table>
	</div>
	<br />
<?php
/* check the old HTTP_POST_VARS and new $_POST var */
	if(!empty($HTTP_POST_VARS))
	{
		$POSTVARIABLE   = $HTTP_POST_VARS;
	}
	else
	{
		$POSTVARIABLE = $_POST;
	}

	if($POSTVARIABLE['action']=='del')
	{
		$id = $POSTVARIABLE['id'];
		del_chat_rec($id);
	}

	if($POSTVARIABLE['action']=='save_option')
	{
		$page_id = $POSTVARIABLE['page_id'];
		save_livechat_adminoption($page_id);
	}
}

function chat_room_init()
{
	global $wpdb;
	$table_name = $wpdb->prefix . "chatroom";
	$sql = "SELECT * FROM $table_name ORDER BY timestamp DESC";
	$chatroom_rec_array = $wpdb->get_results($sql);
	$chatroom_rec_num = $wpdb->num_rows;
	
	$options = get_option("live_chat");
	if ( !is_array( $options ) )
	{
		$options = array(
			"static_mess_record" => "0"
		);
		update_option("live_chat", $options);
	}
?>
	<style>#room div{ margin-top:4px;}#temp_color_div{ margin-top:4px; float:left; background-color:#000;}</style>
	<div class="wrap">
    <h2>Live Chat Room</h2>
	<input id="messNum" type="checkbox" <?php if($options['static_mess_record']) {?> checked <?php }?> /><label for="messNum"> When record number is less than 20,still show 20 record </label></input>
	<input type='button' class='button-secondary action' onclick='set_record_num()' value='Apply'/><br />
	<input type="button" value="Add" onclick='add_room();'/>
	<script type="text/javascript">
		function set_record_num()
		{
			isStaticMessNum = jQuery('#messNum').attr('checked')
			url = document.URL;
			jQuery.post(url,{action:'set_record_num',isStaticMessNum:isStaticMessNum},
				function (msg){
					window.location.reload();
				}
			);
		}
		function edit_room(id){
			var text = jQuery('#room_'+id+'>td:first').html();
			var color = jQuery('#color_'+id+'>div').attr('name');

			jQuery('#room_'+id+'>td:first').html("<input type='text' value='"+text+"' length='100'/>");
			jQuery('#color_'+id).append("<input type='text' id='clr_inpt_"+id+"' value='"+color+"' size='6' onclick='show_picker(this.id,this.value,this.value);'/>");
			jQuery('#clr_inpt_'+id+'_div').css('float','left');
			jQuery('#room_'+id+'>td:last').html("<input type='button' value='Del' name='"+id+"' onclick='del_chatroom(this.name);' /><input type='button' value='Save' name='"+id+"' onclick='edit_chatroom(this.name);' />");
		}
		function add_room(){
			jQuery('tr[id^=room_]:last').after('<tr><td align="center"><input type="text" value="" length="100" /></td><td align="center" id="color"><div style="width:20px;height:20px;" id="temp_color_div">&nbsp</div><input  type="text" value="" size="6" id="temp_color" /></td><td align="center"></td><td align="center"><input type="button" value="Save" onclick="add_chatroom()" /><input type="button" value="Cancel" onclick="cancel_room()" /></td></tr>');
			jQuery('input[value=Add]').hide();
			jQuery("#temp_color").click(function()
			{
				show_picker('temp_color','','');
			});
		}
		function cancel_room(){
			jQuery('input[value=Add]').show();
			jQuery('#room>tbody>tr:last').remove();
		}
		function del_chatroom(id){
			if(confirm("are you sure to delete this?"))
			{
				url = document.URL;
				jQuery.post(url,{action:'del_room',chat_room_id:id},
							function (){
								window.location.reload();
							}
				);
			}
		}
		function edit_chatroom(id){
			var text = jQuery.trim(jQuery('#room_'+id+'>td:first>input:first').attr("value"));
			var color = jQuery.trim(jQuery('#color_'+id+'>input').attr('value'));
			if(!TestColor(color))
			{
				alert(color+" is not a Color code");
				return false;
			}
			if(text == '')
			{
				alert("Can`t input empty Room name ");
				return false;
			}
			url = document.URL;
			jQuery.post(url,{action:'edit_room',chat_room_id:id,title:text,color:color},
				function (){
					window.location.reload();
				}
			);
		}
		function add_chatroom(){
			var text = jQuery.trim(jQuery('#room>tbody>tr:last>td:first>input').attr('value'));
			var color = jQuery.trim(jQuery('#room>tbody>tr:last>td[id=color]>input').attr('value'));
			if(!TestColor(color))
			{
				alert(color+" is not a Color code");
				return false;
			}
			if(text == '')
			{
				alert("Can`t input empty Room name ");
				return false;
			}
			url = document.URL;
			jQuery.post(url,{action:'add_room',title:text,color:color},
				function (msg){
					//jQuery('#feedback').html(msg);
					window.location.reload();
				}
			);
		}
		var which_input;
		// The function name fillColorValue must be used
		// to get the color value. This function takes a string
		// as the color value in a hexidacimal format (e.g. FFFFFF)
		// the function code can be anything the application need.
		function fillColorValue(color){
			document.getElementById(which_input).value = color;
			document.getElementById(which_input+"_div").style.backgroundColor = "#"+color;
		}
		function show_picker(ID, Current_Color, Previous_Color){
			which_input = ID;
			var lnk = "../wp-content/plugins/wp-livechat/js/color_picker_files/color_picker_interface.html\
			?cur_color="+Current_Color+"&pre_color="+Previous_Color;
			window.open(lnk, "", "width=465, height=350");
		}
		function TestColor(value){
            var reg = /^([0-9a-f]{3}|[0-9a-f]{6})$/i;
			return (reg.test(value));
        }	
	</script>
	<div id="feedback"></div>
	<table id="room" width="600" border="1" cellspacing="5" cellpadding="0">
	  <tr id="room_">
		<th width="200">Chat Room Title</th>
		<th width="100">Color</th>
		<th width="150">Create Time</th>
		<th width="150">Operate</th>
	  </tr>
	  <?php
	  foreach($chatroom_rec_array as $chatroom_rec)
	  		{
	  	 		$output .= "<tr id='room_".$chatroom_rec->chat_room_id."'>";
				$output .= "<td align='center'>".$chatroom_rec->title."</td>";
				$output .= "<td align='center' id='color_".$chatroom_rec->chat_room_id."'><div style='background-color:#".$chatroom_rec->color.";width:20px;height:20px;' id='clr_inpt_".$chatroom_rec->chat_room_id."_div' name='".$chatroom_rec->color."'>&nbsp</div></td>";
				$output .= "<td align='center'>".$chatroom_rec->timestamp."</td>";
				$output .= "<td align='center'><input type='button' value='Del' name='$chatroom_rec->chat_room_id' onclick='del_chatroom(this.name);' /><input type='button' value='Edit' name='$chatroom_rec->chat_room_id' onclick='edit_room(this.name);' /></td>";
				$output .= "</tr>";
			}
			echo $output;
	  ?>
	</table>
	</div>
<?php
/* check the old HTTP_POST_VARS and new $_POST var */
	if(!empty($HTTP_POST_VARS))
	{
		$POSTVARIABLE   = $HTTP_POST_VARS;
	}
	else
	{
		$POSTVARIABLE = $_POST;
	}

	if($POSTVARIABLE['action']=='del_room')
	{
		$chat_room_id = $POSTVARIABLE['chat_room_id'];
		del_chatroom($chat_room_id);
	}

	if($POSTVARIABLE['action']=='edit_room')
	{
		$chat_room_id = $POSTVARIABLE['chat_room_id'];
		$title = htmlspecialchars(addslashes($POSTVARIABLE['title']));
		$color = htmlspecialchars(addslashes($POSTVARIABLE['color']));
		edit_chatroom($chat_room_id,$title,$color);
	}

	if($POSTVARIABLE['action']=='add_room')
	{
		$title = htmlspecialchars(addslashes($POSTVARIABLE['title']));
		$color = htmlspecialchars(addslashes($POSTVARIABLE['color']));
		add_chatroom($title,$color);
	}
	
	if($POSTVARIABLE['action']=='set_record_num')
	{
		if ( $POSTVARIABLE['isStaticMessNum'] )
		{
			if($POSTVARIABLE['isStaticMessNum'] == 'true')
			{	
				$options['static_mess_record'] = 1;
			}
			else
			{
				$options['static_mess_record'] = 0;
			}
			update_option("live_chat", $options);
		}
	}

}
/* display the livechat.php */
/*	function Livechat($content) {
		$options = get_livechat_adminoption();
		$multi_page_id = explode(",", $options["page_id"]);

		for($m=0; $m<count($multi_page_id); $m++) {
			if(in_array(is_page($multi_page_id[$m]),$multi_page_id)) {
			$page_id = $multi_page_id[$m];
			$multi_gb_id = $m;
			}
		}

			if(is_page($page_id) AND $page_id!="")
			{
			echo $content;
				$post_id = get_post($page_id);
				if ($_COOKIE['wp-postpass_' . COOKIEHASH] == $post_id->post_password || $post_id->post_password == "") {
				    include('template\guestbook.php');
				}
			}
			else
			{
				return $content;
			}
		}
	add_action('the_content', 'Livechat');
*/
# #	# # # # # - FUNCTIONS - # # # # # # #
	function livechat_install() {
		global $wpdb;
		$table_name = $wpdb->prefix . "chat";
		if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
			$sql = $wpdb->query("CREATE TABLE " . $table_name . " (
				`id` bigint(20) NOT NULL AUTO_INCREMENT,
				`chat_room_id` int(12) NOT NULL,
				`text` longtext NOT NULL,
				`timestamp` DATETIME NOT NULL,
				`sender_id` bigint(20) NOT NULL,
				`receiver_id` bigint(20) NOT NULL,
				`anonymous` int(2) NOT NULL DEFAULT 0, 
				`rating` int(4) NOT NULL DEFAULT 0,
				PRIMARY KEY (`id`),
				INDEX TIME(`timestamp`)
				)DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
			require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
			dbDelta($sql);
		}
		$table_name = $wpdb->prefix . "chatroom";
		if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
			  $sql = $wpdb->query("CREATE TABLE " . $table_name . " (
				`chat_room_id` INT( 12 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
				`title` VARCHAR( 255 ) NOT NULL DEFAULT 'New Chat Room' ,
				`color` VARCHAR( 6 ) NOT NULL DEFAULT '000000',
				`timestamp` DATETIME NOT NULL
				)DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
			require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
			dbDelta($sql);
		}
		get_livechat_adminoption();
	}
	//del chat record
	function del_chat_rec($id = '') {
		global $wpdb;
		$table_name = $wpdb->prefix . "chat";
		if( $id != '')
		{
			$sql = $wpdb->query("DELETE FROM $table_name WHERE id =".$id);
		}
		elseif ($id == '')
		{
			$sql = $wpdb->query("DELETE FROM $table_name");
		}
		else
		{
			echo 'ERROR:WRONG REQUEST';
		}
		require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
		dbDelta($sql);
	}
	//del chat room
	function del_chatroom($id) {
		global $wpdb;
		if( $id != '')
		{	
			require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
			$table_name = $wpdb->prefix . "chatroom";
			$sql = $wpdb->query("DELETE FROM $table_name WHERE chat_room_id =".$id);
			dbDelta($sql);
			$table_name = $wpdb->prefix . "chat";
			$sql = $wpdb->query("DELETE FROM $table_name WHERE chat_room_id =".$id);	
			dbDelta($sql);		
		}
		else
		{
			echo 'ERROR:WRONG REQUEST';
		}
		
		
	}
	function add_chatroom($title,$color){
		//var_dump($title.$color);exit;
		global $wpdb;
		$table_name = $wpdb->prefix . "chatroom";
		$sql = $wpdb->query("INSERT INTO $table_name (`chat_room_id` ,`title` ,`color` ,`timestamp`)VALUES (NULL , '".$title."', '".$color."', now())");
		require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
		dbDelta($sql);
	}

	function edit_chatroom($id,$title,$color){
		global $wpdb;
		$table_name = $wpdb->prefix . "chatroom";
		$sql = $wpdb->query("UPDATE $table_name SET `title` = '".$title."', `color` = '".$color."' WHERE `chat_room_id` = ".$id." LIMIT 1 ");
		require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
		dbDelta($sql);
	}

	//save adminoptions
	function save_livechat_adminoption($page_id) {
		$livechatAdminOptions = array("page_id" => $page_id);
		update_option("livechat_options", $livechatAdminOptions);
	}
	//Returns an array of admin options
	function get_livechat_adminoption() {
		$livechatAdminOptions = array("page_id" => "-")	;
		$devOptions = get_option("livechat_options");
		if(!empty($devOptions))
		{
			foreach ($devOptions as $key => $option)
				$livechatAdminOptions[$key] = $option;
		}
		update_option("livechat_options", $livechatAdminOptions);
		return $livechatAdminOptions;
	}
	function get_user($id)
	{
		global $wpdb;
		$table_name = $wpdb->prefix . 'users';
		$sql = "SELECT * FROM $table_name WHERE ID = $id";
		$users_array = $wpdb->get_results($sql);
		return $users_array[0];
	}
function set_profiler_page() {
	$options = get_option("live_chat");
	if ( !is_array( $options ) )
	{
		$options = array(
			"profiler_page_id" => "0"
		);
		update_option("live_chat", $options);
	}

	if ( $_POST['profiler_page_id'] )
	{
		$options['profiler_page_id']   = htmlspecialchars($_POST['profiler_page_id']);
		update_option("live_chat", $options);
	}
	echo "<form name='profiler_page' class='form-table' action='".$_SERVER['REQUEST_URI']."' method='post' style='margin-top: 20px;'>Profiler Page Id: <input type='text'  length='6' id='profiler_page_id' name='profiler_page_id' value='".$options['profiler_page_id']."'/><input type='submit' class='button-secondary action' value='Apply'/></form>";
}
function gg_options_page_chat() {
	  $wpv = get_bloginfo('version');
	  echo '<div class="wrap">';
    echo '<h2>ChatRoom Generator</h2>';
    if ($_POST['generate']) {
	  include('guestbook_utility.php');
	  $gb = generate_guestbook();
	  echo $gb;
  } else {
  	if ($wpv < 2.1) {
  	echo '<span style="color: red; font-weight: bold;">Warning:</span>Chatroom is based on Wordpress2.6 above,if you can`t install successfully please upgrade your Wordpress.<br />';
    echo '<p class="submit"><input type="submit" name="generate" value="Generate ChatRoom &raquo;" style="color:#cccccc;"/></p>';
    } else {
    echo 'This operation generate Chat Room template.<br />';
    echo 'If you change your theme , please generate again in order to create <strong>livechat.php</strong> in your new theme folder';
    echo '<form method="post" action="">';
    echo '<p class="submit"><input type="submit" name="generate" value="Generate LiveChat &raquo;" /></p>';
    echo '</form>';
         }
    }
    echo '</div>';
}
?>